package com.jycrm.dao.serve.impl;

import java.util.List;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;

import org.springframework.orm.hibernate.HibernateCallback;

import com.jycrm.common.PagedListHolder;
import com.jycrm.dao.core.AbstractService;
import com.jycrm.dao.serve.IReckoningConversionFileDao;
import com.jycrm.domain.serve.reckoning.ReckoningConversionFile;

public class ReckoningConversionFileDaoImpl extends AbstractService implements
		IReckoningConversionFileDao {

	public void save(ReckoningConversionFile file) {
		this.persistenceManager.create(file);

	}

	public void update(ReckoningConversionFile file) {
		this.persistenceManager.update(file);

	}

	public void delete(ReckoningConversionFile file) {
		this.persistenceManager.delete(file);

	}

	public ReckoningConversionFile getReckoningConversionFileById(Long id) {
		return (ReckoningConversionFile) queryManager.getObjectById(
				ReckoningConversionFile.class, id);
	}

	public PagedListHolder getReckoningConversionFilePagedListHolder(
			final ReckoningConversionFileParam param, final int pageSize,
			final int pageNo) {

		PagedListHolder p = (PagedListHolder) this.queryManager
				.execute(new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {

						StringBuffer queryStr = new StringBuffer(
								"FROM ReckoningConversionFile as d where 1=1 ");
						if (param.getCreator() != null) {
							queryStr
									.append(" and d.creator.userName like :creator ");
						}
						if (param.getStartDate() != null) {
							queryStr.append(" and  to_date(to_char(d.createDate,'yyyy-mm-dd'),'yyyy-mm-dd')  >=:startDate ");
						}
						if (param.getEndDate() != null) {
							queryStr.append(" and to_date(to_char(d.createDate,'yyyy-mm-dd'),'yyyy-mm-dd') <=:endDate ");
						}
						if (param.getAlias() != null) {
							queryStr.append(" and d.alias like :alias ");
						}
						queryStr.append(" order by d.id desc");
						StringBuffer queryCount = new StringBuffer(
								"SELECT COUNT(*) " + queryStr.toString());
						Query query1 = session.createQuery(queryCount
								.toString());
						query1.setProperties(param);
						int total = ((Integer) query1.iterate().next())
								.intValue();
						PagedListHolder pagedListHolder = new PagedListHolder();
						pagedListHolder.setPageSize(pageSize);
						pagedListHolder.setTotal(total);
						pagedListHolder.setPage(pageNo);

						Query query = session.createQuery(queryStr.toString());
						query.setProperties(param);
						query.setMaxResults(pagedListHolder.getPageSize());
						query.setFirstResult(pagedListHolder.getPage()
								* pagedListHolder.getPageSize());
						List rs = query.list();
						pagedListHolder.setPageList(rs);
						return pagedListHolder;
					}

				});
		return p;
	}

}
